//app.js
import HttpRequest from 'utils/HttpRequest'
import WxService from 'utils/WxService'
import Util from 'utils/util'
import es6 from 'lib/es6-promise'

App({
  onLaunch () {
    //调用API从本地缓存中获取数据
    // var logs = wx.getStorageSync('logs') || []
    // logs.unshift(Date.now())
    // wx.setStorageSync('logs', logs)
    this.objectAssignPolyfill()
  },
  objectAssignPolyfill(){
    if (typeof Object.assign != 'function') {
      Object.assign = function(target) {
        'use strict';
        if (target == null) {
          throw new TypeError('Cannot convert undefined or null to object');
        }

        target = Object(target);
        for (var index = 1; index < arguments.length; index++) {
          var source = arguments[index];
          if (source != null) {
            for (var key in source) {
              if (Object.prototype.hasOwnProperty.call(source, key)) {
                target[key] = source[key];
              }
            }
          }
        }
        return target;
      };
    }
  },
  getLocation(){
    const self = this
    return new es6.Promise((resolve, reject) => {
      if(!this.globalData.locationData){
        wx.getLocation({
          type: 'wgs84',
          success(res) {
            console.log(res);
            self.globalData.locationData = res
            resolve(res)
          },
          fail(){
            console.log('用户拒绝授权地址');
            resolve({})
          }
        })
      } else {
        resolve(this.globalData.locationData)
      }
    })
  },
  /**
   * 登录流程：
   * 1.页面pages中调用getApp().getUser()异步接口即可获取userInfo。方法会缓存userInfo，不需要担心重复请求
   * 2.getUser方法已缓存session。需要时可以从从storage中提取
   * 3.
   */
  getUser(){
    const self = this
    return new es6.Promise((resolve, reject) => {
      if(!this.globalData.userData){
        //获取session方法
        es6.Promise.resolve()
        .then(() => {
          return this.util.getSession()
        })
        .then(session => {
          wx.getUserInfo({
            success(data){
              self.globalData.userData = data
              resolve(data)
            },
            fail(){
              reject(new Error ('User denies'))
            }
          })
        })
      } else {
        resolve(this.globalData.userData)
      }
    })
  },
  //请注意参数顺序
  registerUser({ encryptedData, iv }, { latitude=0, longitude=0 }){
    const self = this
    return new es6.Promise((resolve, reject) => {
      this.$http.POST('/welcome/register', {
        encryptedData,
        iv,
        latitude,
        longitude,
      })
      .then(data => {
        resolve(data)
      })
      .catch(e => {
        reject(e)
      })
    })
  },
  globalData:{
    userData:null,
    picDetail: '',
    locationData: null,
  },
  $http: new HttpRequest,
  $wx: new WxService,
  util: new Util
})
